package com.rong.common.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.king.util.file.json.JsonUtil;
import com.king.util.http.HttpUtil;
import com.rong.common.context.Context;

public class HttpRequestUtil extends HttpUtil
{
	public static String doGetP2P( Map<String,Object> params , String url , boolean isLogin ) throws Exception
	{
		String returnCode ="" ;//返回结果代码
		HttpClient httpClient = new HttpClient();
		/*生成get对象*/
		GetMethod getMethod = new GetMethod( url + "?" +getParamSet( params ) );
		
		/* 判断是否已登陆 
		if( isLogin )
		{
			params.put("mobile", "true");
			getMethod.setRequestHeader(new Header("loginUser", Context.getStringParam("loginUser")));
		}	 */
		getMethod.setRequestHeader(new Header("isLogin", ""+isLogin));
		
		getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8"); 
		// 使用系统提供的默认的恢复策略
		getMethod.getParams().setParameter( HttpMethodParams.RETRY_HANDLER ,
				new DefaultHttpMethodRetryHandler() ) ;
		/*执行get方法*/
		int statusCode = httpClient.executeMethod( getMethod ) ;
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());/*请求成功*/
		if( statusCode == HttpStatus.SC_OK )
		{
			//解析返回代码
			returnCode = convertInputStream( getMethod.getResponseBodyAsStream());
			checkLogin(params, returnCode);
		}
		else
		{
			returnCode = String.valueOf( statusCode );
		}
		
		/*释放链接*/
		getMethod.releaseConnection() ;
		return returnCode;
	}
	
	private static void checkLogin( Map<String,Object> params , String json ) 
	{
		String p = params.get("p").toString();
		String m = params.get("m").toString();
		
		if( "login".equals(p) && "login".equals(m) )
		{
			Map map = (Map)JsonUtil.getInstance("UTF-8").parseJsonToObject(json, Map.class);
			HttpSession session = (HttpSession)Context.getParam("@session");
			session.setAttribute("loginUser", map.get("loginUser"));
		}	
	}
	
	/**
	 * 构建请求参数
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private static String getParamSet( Map<String,Object> params ) throws Exception
	{
		/*构建请求参数*/
		StringBuffer paramBuffer = new StringBuffer();
		paramBuffer.append( "" );
		if( null!= params )
		{
			Set<String> keys = params.keySet();
			int i = 0;
			for( String key : keys )
			{
				if("".equals(params.get( key )) || params.get( key )==null){
					if( i == 0 )
					{
						paramBuffer.append( key + "=" + params.get( key ));
					}
					else
					{
						paramBuffer.append( "&" + key + "=" + params.get( key ));
					}
				}else{
					
					if( null!=params.get( key ) )
					{
						if( i == 0 )
						{
							paramBuffer.append( key + "=" + URLEncoder.encode(params.get( key ).toString(),"UTF-8") );
						}
						else
						{
							paramBuffer.append( "&" + key + "=" + URLEncoder.encode(params.get( key ).toString(),"UTF-8")  );
						}
					}
				}
				i++;
			}
		}
		return paramBuffer.toString();
	}
	
	private static String convertInputStream( InputStream is ) throws Exception
	{
		StringBuffer sb = new StringBuffer();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
		String line;
		while( (line = reader.readLine() )!=null)
		{
			sb.append(line);
		}
		return sb.toString();
	}
}
